<?php
namespace app\credit\controller;

use app\common\cache\agent\IAgentAdminCache;
use app\common\cache\user\IUserCache;
use app\common\cache\total\PoolBidCache;
use app\common\controller\CreditBaseController;
use app\common\enum\AppType;
use app\common\enum\PoolBidStatus;
use app\common\enum\TenderStatus;
use app\common\ext\IBid;
use app\common\ext\IConfig;
use app\common\ext\IDb;
use app\common\ext\IJPush;
use app\common\ext\UserPoolBid;
use app\common\ext\IUrl;

class Bid extends CreditBaseController {

    /**
     * @功能：首页
     * @开发者：gys
     */
    public function index(){

        //获取真实个数和金额
        $order_num = PoolBidCache::getPoolBidNumInfo();
        $order_amount = PoolBidCache::getPoolBidMoneyInfo();

        //获取配置个数和金额
        $PoolBidNum = IConfig::getValue("PoolBidNum");
        $PoolBidMoney = IConfig::getValue("PoolBidMoney");
        $order_num = $order_num['order_num']+intval($PoolBidNum);
        $order_amount = $order_amount['order_amount']+intval($PoolBidMoney);

        $where['pool_bid_status'] = PoolBidStatus::BidStop;
        $order_list = IDb::getInstance('user_pool_bid as upb')
            ->setDbFiled('upb.user_pool_bid_id,upb.open_time,upb.bid_no,upb.money,upb.period,upb.user_id,upb.agent_admin_id')
            ->setDbWhere($where)
            ->setDbOrder("user_pool_bid_id desc")
            ->setDbLimit(5)
            ->sel();
        if (!empty($order_list)){
            foreach ($order_list as $key=>&$order){

                if(empty($order['agent_admin_id']) || empty($order['user_id'])){
                    continue;
                }
                $admin_info = IAgentAdminCache::getInfo($order['agent_admin_id'],['real','business_phone']);
                $order['agent_admin_real'] = mb_substr($admin_info['real'],0,1).'经理';
                $order['agent_admin_phone'] = get_string_rsa($admin_info['business_phone'],3,4);

                $user_info = IUserCache::getInfo($order['user_id'],['real','sex','loan_phone']);
                $order['user_real'] = get_real_cover($user_info['real'],$user_info['sex']);
                $order['user_phone'] = get_string_rsa($user_info['loan_phone'],3,4);

                $time = time_diff($order['open_time'],get_date_time());
                if ($time['day']>=1){
                    $order['time'] = '1天前';
                }else if($time['hours']>=1){
                    $order['time'] = $time['hours'].'小时前';
                }else if ($time['minutes']>=1){
                    $order['time'] = $time['minutes'].'分钟前';
                }else{
                    $order['time'] = '1分钟前';
                }
            }
        }else{
            $order_list = array(
                0=>array(
                    'user_pool_bid_id' => 361,
                    'open_time' =>  '2019-04-14 22:39:49' ,
                    'bid_no' =>  188361,
                    'money' =>  2,
                    'period' =>  12,
                    'user_id' =>  741,
                    'agent_admin_id' =>  164,
                    'agent_admin_real' =>  '王经理',
                    'agent_admin_phone' =>  '188****7245',
                    'user_real' =>  '林女士',
                    'user_phone' =>  '182****7593',
                    'time' => '1天前',
                )
            );
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("order_num",$order_num);
        self::set_value("order_amount",$order_amount);
        self::set_value("order_list",$order_list);
        self::send();
    }

    /**
     * @功能：搜索选项
     * @开发者：gys
     */
    public function search_item(){
        $search_type = [
            ['item'=>'is_car','title'=>'有车'],
            ['item'=>'is_house','title'=>'有房产'],
            ['item'=>'is_credit_card','title'=>'有信用卡'],
            ['item'=>'is_accumulation_fund','title'=>'有公积金'],
            ['item'=>'is_policy','title'=>'有保单'],
            ['item'=>'is_social','title'=>'有社保'],
            ['item'=>'is_company','title'=>'有公司'],
        ];

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("search_type",$search_type);
        self::send();
    }

    /**
     * @功能：订单列表
     * @开发者：gys
     */
    public function bid_list(){
        $province_id = self::get_data('province_id');
        $city_id = self::get_data('city_id');
        $money_min = self::get_data('money_min');
        $money_max = self::get_data('money_max');
        $age_min = self::get_data('age_min');
        $age_max = self::get_data('age_max');
        $asset = self::get_data('asset');
        $bottom_id = self::get_data('bottom_id');

        $asset_array = explode('|',$asset);
        $asset_array = array_intersect(['is_car','is_house','is_credit_card','is_accumulation_fund','is_policy','is_social','is_company'],$asset_array);
        foreach ($asset_array as $asset){
            $where['u.'.$asset] = 2;
        }

        if(!empty($province_id)) $where['upb.province_id'] = $province_id;
        if(!empty($city_id)) $where['upb.city_id'] = $city_id;
        if(!empty($money_min)) $where['upb.money'] = array("egt",$money_min);
        if(!empty($money_max)) {
            if(!empty($money_min)){
                $where["upb.money"] = [$where["upb.money"],['elt',$money_max,'and']];
            }else{
                $where["upb.money"] = ['elt',$money_max];
            }
        }
        if(!empty($age_min)) $where['u.age'] = array("egt",$age_min);
        if(!empty($age_max)) {
            if(!empty($age_min)){
                $where["u.age"] = [$where["u.age"],['elt',$age_max,'and']];
            }else{
                $where["u.age"] = ['elt',$age_max];
            }
        }
        if(!empty($bottom_id)) $where['concat(1,lpad(user_pool_bid_id,8,0))'] = array("lt",$bottom_id);

        $where['pool_bid_status'] = PoolBidStatus::Bid;
        $where['bid_end'] = ['gt',date('Y-m-d H:i:s')];

        $list = IBid::getList($where);
        foreach ($list as &$val){
            //判断是否投过标
            $tender_where['user_pool_bid_id'] = $val['user_pool_bid_id'];
            $tender_where['agent_admin_id'] = self::$uid;
            $tender_info = IDb::getInstance('agent_admin_tender')
                ->setDbFiled('tender_status')
                ->setDbWhere($tender_where)
                ->row();
            if($tender_info){
                $val['tender_status'] = $tender_info['tender_status'];
                $expire_hour = get_config('OpenBidDate',0);
                $val['bid_end_timestamp'] = $val['bid_end_timestamp']+intval($expire_hour)*3600;
            }else{
                $val['tender_status'] = 0;
            }

            $val['not_log_day'] = 0;
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("bid_list",$list);
        self::send();
    }


    /**
     * @功能：订单详情
     * @开发者：gys
     */
    public function bid_info(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");

        $where['user_pool_bid_id'] = $user_pool_bid_id;
//        $where['pool_bid_status'] = PoolBidStatus::Bid;

        $bid_info = IBid::getInfo($where);
        if(!$bid_info){
            self::set_code(self::WARNING_0001);
            self::set_msg(IBid::getError());
            self::send();
        }

        $user_info = IUserCache::getInfo($bid_info['user_id'],['real','sex','loan_phone']);
        $bid_info['loan_phone'] = $user_info['loan_phone'];
        $bid_info['real'] = $user_info['real'];

        //只有在中标和已结标才可以查看用户征信报告
        $report_url = '';

        $is_bid = true;

        //判断是否投过标
        $tender_where['user_pool_bid_id'] = $user_pool_bid_id;
        $tender_where['agent_admin_id'] = self::$uid;
        $tender_info = IDb::getInstance('agent_admin_tender')
            ->setDbFiled('agent_admin_tender_id,tender_status,open_time')
            ->setDbWhere($tender_where)
            ->row();
        if(empty($tender_info)){
            $tender_info = [];
            $bid_info['open_time'] = '';
            $bid_info['tender_status'] = '0';
            $bid_info['loan_phone'] = IBid::coverPhone($bid_info['loan_phone']);
            $bid_info['real'] = get_real_cover($user_info['real'],$user_info['sex']);
        }else{
            //已抢单后过期时间以开标截止时间为准
            $bid_info['bid_end_timestamp'] = $bid_info['bid_expire_timestamp'];
            $bid_info['bid_end'] = date('Y-m-d',$bid_info['bid_expire_timestamp']);

            $bid_info['open_time'] = substr($tender_info['open_time'],0,10);
            $bid_info['tender_status'] = $tender_info['tender_status'];
            if(!in_array($tender_info['tender_status'] ,array(TenderStatus::Bid,TenderStatus::BidStop))){
                $bid_info['loan_phone'] = IBid::coverPhone($bid_info['loan_phone']);
                $bid_info['real'] = get_real_cover($user_info['real'],$user_info['sex']);
            }else{
                $is_bid = false;
                $report_url = IUrl::getCredit($bid_info['user_id']);
            }
        }

        $data = \app\common\ext\User::getAsset($bid_info['user_id'],$is_bid);

        $data['bid_info'] = $bid_info;
        $data['tender_info'] = $tender_info;
        $data['report_url'] = $report_url;

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_values($data);
        self::send();
    }

    /**
     * @功能：投标
     * @开发者：gys
     */
    public function bid_tender(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");
        $tender_note  = self::get_data('tender_note');

        $bid_info = UserPoolBid::tender(self::$uid,$user_pool_bid_id,$tender_note);
        if($bid_info === -1){
            //此处错误码不可更改
            self::set_code(self::ERR_0005);
            self::set_msg(UserPoolBid::getError());
            self::send();
        }elseif(!$bid_info){
            self::set_code(self::WARNING_0001);
            self::set_msg(UserPoolBid::getError());
            self::send();
        }

        //取得用户电话号码
//        $user_phone = IUserCache::getInfo($user_pool_bid_info['user_id'],"phone");

        //判断用户电话号码是否存在
//        if(!empty($user_phone)){
//            //发送短信
//            ISms::Send($user_phone,ISms::PrTender);
//        }

        //发送推送信息
        IJPush::Push(AppType::HZ,"信贷经理抢单成功！","有信贷经理抢了您的订单；",$bid_info['cooperate_admin_id']);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

}
